let _Vue = null;

export default class VueRouter {
    static install(Vue) {
        // 判断是否已经注入把router注入到vue中
        if (VueRouter.install.installed && _Vue === Vue) return
        VueRouter.install.installed = true;
        // 记录变量
        _Vue = Vue;
        // 在创建Vue实例时，把传入的router对象注入到Vue实例上，所有的组件都能获取到，那就是注入到_Vue的原型上
        _Vue.mixin({
            beforeCreate() {
                if (this.$options.router) {
                    _Vue.prototype.$router = this.$options.router;
                    this.$options.router.init()
                }
            }
        })
    }

    constructor(options) {
        this.options = options;
        this.routeMap = {};
        this.data = _Vue.observable({
            current: '/'
        })
    }

    init() {
        this.createRouteMap();
        this.initComponents(_Vue);
        this.initEvent();
    }

    // 将传入的routes对象转换成键值对形式的数据存入在routeMap中
    createRouteMap() {
        this.options.routes.forEach(route => {
            this.routeMap[route.path] = route.component;
        })
    }

    initComponents(Vue) {
        Vue.component('router-link', {
            props: {
                to: String,
            },
            methods: {
                clickHandler(event) {
                    event.preventDefault();
                    history.pushState({}, '', this.to);
                    this.$router.data.current = this.to;
                }
            },
            render(createElement) {
                return createElement('a', {
                    attrs: {
                        href: this.to
                    },
                    on: {
                        click: this.clickHandler
                    }
                }, [this.$slots.default])
            }
        })

        const self = this;
        Vue.component('router-view', {
            render(createElement) {
                const component = self.routeMap[self.data.current]
                return createElement(component)
            }
        })
    }

    initEvent() {
        window.addEventListener('popstate', () => {
            this.data.current = window.location.pathname
        })
    }
}